import java.io.*;
import java.util.Scanner;


//读取指定行数据
public class specifyTheLineTest {
    public static void main(String[] args) throws Exception {
        // 读取文件
        String fileName = "C:\\Users\\Administrator\\Desktop\\ccccc\\22_03_31Receive.txt";
        // 获取文件的内容的总行数
        int totalNo = getTotalLines(fileName);
        System.out.println("本文总共有：" + totalNo + "行");
        while (true) {
            Scanner sc = new Scanner(System.in);
            // 指定读取的行号
            int lineNumber = sc.nextInt();
            //读取指定行的内容
            readLineVarFile("C:\\Users\\Administrator\\Desktop\\ccccc\\22_03_31Receive.txt", lineNumber);
        }

    }

    /**
     * 读取txt文件的内容
     *
     * @param fileName 想要读取的文件对象
     * @return 返回文件内容
     */

    public static void readLineVarFile(String fileName, int lineNumber) throws IOException {
        //使用缓冲区的方法将数据读入到缓冲区中
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
        //定义行数
        String line = reader.readLine();
        //确定输入的行数是否有内容
        if (lineNumber <= 0 || lineNumber > getTotalLines(fileName)) {
            System.out.println("不在文件的行数范围之内。");
        }
        int num = 0;
        //当行数不为空时，输出该行内容及字符数
        while (line != null) {
            if (lineNumber == ++num) {
                System.out.println("第" + lineNumber + "行: " + line + "     字符数为：" + line.length());
            }
            line = reader.readLine();
        }
        reader.close();

    }

    // 文件内容的总行数
    static int getTotalLines(String fileName) throws IOException {
        //使用缓冲区的方法将数据读入到缓冲区中
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
        LineNumberReader reader = new LineNumberReader(br);
        //定义行数
        String s = reader.readLine();
        int lines = 0;
        //确定行数
        while (s != null) {
            lines++;
            s = reader.readLine();
        }
        reader.close();
        br.close();
        //返回行数
        return lines;
    }


}
